<template>
  <div class="ai-reply-container" v-if="showReply">
    <!-- 右侧 AI 回复等功能区 -->
    <!-- {{ review }} -->

    <div v-if="review.reviewReplyDTO.isReply == true">
      <div
        class="username"
        style="
          font-size: 0.125rem;
          font-weight: 700;
          color: #454545;
          margin-bottom: 12px;
        "
      ></div>
      <div
        style="
          font-size: 0.125rem;
          font-weight: 700;
          color: #454545;
          margin-bottom: 20px;
        "
      >
        Replied
      </div>
      <div
        style="
          font-family: 'Inter Variable', sans-serif;
          font-size: 0.0972rem;
          font-weight: 400;
          color: #232323;
          line-height: 1.6;
          letter-spacing: 0.5px;
        "
      >
        <!-- 处理带翻译和原始内容的展示 - 保留标记 -->
        <template v-if="hasTranslatedAndOriginal(review.reviewReplyDTO.replyComments)">
          <!-- 翻译内容段（包含标记） -->
          <div class="translated-content">
            {{ getTranslatedSection(review.reviewReplyDTO.replyComments) }}
          </div>
          <!-- 原始内容段（包含标记，添加间距） -->
          <div class="original-content" style="margin-top: 16px;">
            {{ getOriginalSection(review.reviewReplyDTO.replyComments) }}
          </div>
        </template>
        <!-- 普通内容直接展示 -->
        <template v-else>
          {{ review.reviewReplyDTO.replyComments }}
        </template>
      </div>
    </div>
    <div class="ai-reply-card" v-else>
      <div class="ai-reply-header">
        <div class="header-title">
          <div class="section-label">AI Reply</div>
          <div class="preview-toggle-btn">Preview full reply</div>
        </div>
        <div class="header-actions">
          <CustomDropdownc
            v-model="selectedLanguage"
            :options="toneOptions"
            @change="handleLanguageChange"
            prefix-text="Tone"
          />
          <div class="feedback-icon">
            <img src="@/assets/pieIcon/like.png" alt="" />
          </div>
        </div>
      </div>

      <div class="form-fields-container" ref="formContainer">
        <div class="form-group" ref="titleGroup">
          <label class="form-label" for="title">Title</label>
          <div class="form-control-wrapper">
            <textarea
              class="form-textarea title-textarea"
              id="title"
              draggable="false"
              ref="titleTextarea"
            ></textarea>
            <div class="compact-pagination">
              <div
                class="pagination-icon"
                @click="prevPage"
                style="width: 0.0417rem; height: 0.0556rem"
              >
                <img src="@/assets/left.png" />
              </div>
              <span class="pagination-info compact">
                {{ currentPage }}/{{ totalPages }}
              </span>
              <div
                class="pagination-icon"
                @click="nextPage"
                style="width: 6px; height: 8px"
              >
                <img src="@/assets/right.png" />
              </div>
            </div>
          </div>
        </div>

        <div class="form-group" ref="startGroup">
          <label class="form-label" for="start">Start</label>
          <div class="form-control-wrapper">
            <textarea
              ref="startTextarea"
              class="form-textarea start-textarea"
              id="start"
              draggable="false"
            ></textarea>
            <div class="compact-pagination">
              <div
                class="pagination-icon"
                @click="prevPage"
                style="width: 6px; height: 8px"
              >
                <img src="@/assets/left.png" />
              </div>
              <span class="pagination-info compact">
                {{ currentPage }}/{{ totalPages }}
              </span>
              <div
                class="pagination-icon"
                @click="nextPage"
                style="width: 6px; height: 8px"
              >
                <img src="@/assets/right.png" />
              </div>
            </div>
          </div>
        </div>

        <div class="form-group" ref="mainGroup">
          <label class="form-label" for="mainBody">Main Body</label>
          <div class="form-control-wrapper">
            <textarea
              class="form-textarea main-textarea"
              id="mainBody"
              draggable="false"
              ref="mainBodyTextarea"
            ></textarea>
            <div class="compact-pagination">
              <div
                class="pagination-icon"
                @click="prevPage"
                style="width: 6px; height: 8px"
              >
                <img src="@/assets/left.png" />
              </div>
              <span class="pagination-info compact">
                {{ currentPage }}/{{ totalPages }}
              </span>
              <div
                class="pagination-icon"
                @click="nextPage"
                style="width: 6px; height: 8px"
              >
                <img src="@/assets/right.png" />
              </div>
            </div>
          </div>
        </div>

        <div class="form-group" ref="endingGroup">
          <label class="form-label" for="ending">Ending</label>
          <div class="form-control-wrapper">
            <textarea
              class="form-textarea ending-textarea"
              id="ending"
              ref="endingTextarea"
              draggable="false"
            ></textarea>
            <div class="compact-pagination">
              <div
                class="pagination-icon"
                @click="prevPage"
                style="width: 6px; height: 8px"
              >
                <img src="@/assets/left.png" />
              </div>
              <span class="pagination-info compact">
                {{ currentPage }}/{{ totalPages }}
              </span>
              <div
                class="pagination-icon"
                @click="nextPage"
                style="width: 6px; height: 8px"
              >
                <img src="@/assets/right.png" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="action-bar" ref="actionBar">
        <CustomDropdownc
          v-model="selectedLanguage"
          :options="languageOptions"
          @change="handleLanguageChange"
          prefix-text="Language"
        />
        <div class="action-buttons" ref="actionButtons">
          <button class="action-btn edit-btn">Edit</button>
          <button class="action-btn send-btn">Send</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CustomDropdownc from "./CustomDropdownc.vue";

export default {
  components: { CustomDropdownc },
  data() {
    return {
      total: 100,
      currentPage: 1,
      pageSize: 25,
      disabled: false,
      selectedLanguage: [],
      languageOptions: [
        { value: "english", label: "English" },
        { value: "french", label: "French" },
        { value: "german", label: "German" },
        { value: "italian", label: "Italian" },
      ],
      toneOptions: [
        { value: "Warm", label: "Warm" },
        { value: "Sorry", label: "Sorry" },
        { value: "Thanks", label: "Thanks" },
      ],
      // 高度比例配置
      heightRatios: {
        title: 1, // Title区域占比
        start: 4, // Start区域占比（3-5倍）
        main: 8, // Main Body区域占比（7-10倍）
        ending: 1, // Ending区域占比
      },
      // 基础高度配置
      baseMinHeight: 30,
      baseMaxHeight: 600,
      // 联动配置
      leftContentRef: null, // 左侧内容引用
      isListening: false, // 监听状态
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    },
  },
  props: {
    // 接收左侧内容高度
    leftContentHeight: {
      type: Number,
      default: 400,
    },
    showReply: {
      type: Boolean,
      default: false, // 默认隐藏
    },
    review: {
      type: Object,
      required: true,
      default: () => ({}),
    },
    // 接收左侧底部按钮高度
    leftButtonsHeight: {
      type: Number,
      default: 40,
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initHeightCalculation();
      this.observeContainerSize();
      this.listenToLeftContent();
      this.listenToWindowResize();
    });
    // 监听父组件传递的props变化
    this.$watch(
      () => [this.leftContentHeight, this.leftButtonsHeight],
      () => {
        this.calculateTextareaHeight();
        this.alignBottomButtons();
      },
      { deep: true }
    );
  },
  beforeDestroy() {
    if (this.observer) this.observer.disconnect();
    if (this.resizeListener)
      window.removeEventListener("message", this.resizeListener);
    if (this.windowResizeListener)
      window.removeEventListener("resize", this.windowResizeListener);
  },
  watch: {
    leftContentHeight() {
      this.calculateTextareaHeight();
    },
  },
  methods: {
    // 判断是否包含翻译和原始内容标记
    hasTranslatedAndOriginal(content) {
      if (!content) return false;
      // 同时包含两个标记才进行分段
      return content.includes('(Translated by Google)') && content.includes('(Original)');
    },

    // 获取包含翻译标记的完整段落
    getTranslatedSection(content) {
      const originalIndex = content.indexOf('(Original)');
      return content.substring(0, originalIndex).trim();
    },

    // 获取包含原始内容标记的完整段落
    getOriginalSection(content) {
      const originalIndex = content.indexOf('(Original)');
      return content.substring(originalIndex).trim();
    },

    // 分页方法
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.fetchData();
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.fetchData();
      }
    },
    initHeightCalculation() {
      this.calculateTextareaHeight();
    },
    listenToWindowResize() {
      this.windowResizeListener = () => {
        this.calculateTextareaHeight();
        this.alignBottomButtons();
      };
      window.addEventListener("resize", this.windowResizeListener);
    },
    listenToLeftContent() {
      if (this.isListening) return;

      this.resizeListener = (e) => {
        if (e.data && e.data.type === "leftContentResized") {
          this.leftContentHeight = e.data.height;
          this.leftButtonsHeight = e.data.buttonsHeight;
          this.calculateTextareaHeight();
          this.alignBottomButtons();
        }
      };

      window.addEventListener("message", this.resizeListener);
      this.isListening = true;
    },
    observeContainerSize() {
      this.observer = new ResizeObserver((entries) => {
        for (const entry of entries) {
          if (entry.target === this.$refs.formContainer) {
            this.calculateTextareaHeight();
          }
        }
      });

      if (this.$refs.formContainer) {
        this.observer.observe(this.$refs.formContainer);
      }
    },
    calculateTextareaHeight() {
      const availableHeight = this.leftContentHeight * 0.8;
      const windowHeight = window.innerHeight - 200;
      const maxAvailableHeight = Math.min(availableHeight, windowHeight * 0.6);
      const ratioSum = Object.values(this.heightRatios).reduce(
        (sum, ratio) => sum + ratio,
        0
      );
      const baseHeight = maxAvailableHeight / ratioSum;

      const titleHeight = Math.max(
        this.baseMinHeight,
        Math.min(this.baseMaxHeight * 0.1, baseHeight * this.heightRatios.title)
      );
      const startHeight = Math.max(
        this.baseMinHeight,
        Math.min(this.baseMaxHeight * 0.3, baseHeight * this.heightRatios.start)
      );
      const mainHeight = Math.max(
        this.baseMinHeight,
        Math.min(this.baseMaxHeight * 0.5, baseHeight * this.heightRatios.main)
      );
      const endingHeight = Math.max(
        this.baseMinHeight,
        Math.min(
          this.baseMaxHeight * 0.1,
          baseHeight * this.heightRatios.ending
        )
      );

      this.setAllTextareaHeight({
        title: titleHeight,
        start: startHeight,
        main: mainHeight,
        ending: endingHeight,
      });
    },
    setAllTextareaHeight(heights) {
      const textareas = {
        title: this.$refs.titleTextarea,
        start: this.$refs.startTextarea,
        main: this.$refs.mainBodyTextarea,
        ending: this.$refs.endingTextarea,
      };

      Object.keys(textareas).forEach((key) => {
        const textarea = textareas[key];
        if (!textarea) return;

        textarea.style.height = `${heights[key]}px`;

        const textareaEl = textarea.$el || textarea;
        if (textareaEl?.className) {
          textareaEl.className = textareaEl.className.replace(
            /title-textarea|start-textarea|main-textarea|ending-textarea/,
            ""
          );
        }

        textareaEl.classList.add(`${key}-textarea`);
      });
    },
    alignBottomButtons() {
      if (!this.$refs.actionBar || !this.leftButtonsHeight) return;
      const actionBarHeight = this.$refs.actionBar.offsetHeight;
      const marginBottom = this.leftButtonsHeight - actionBarHeight;
      if (marginBottom > 0) {
        this.$refs.actionBar.style.marginBottom = `${marginBottom}px`;
      }
    },
    handleLanguageChange(lang) {
      console.log("下拉框选中的值是", lang);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
      console.log(`每页显示 ${val} 条，总页数 ${this.totalPages}`);
    },
    handleCurrentChange(val) {
      this.currentPage = Math.min(val, this.totalPages);
      this.fetchData();
      console.log(`当前页码 ${this.currentPage}，总页数 ${this.totalPages}`);
    },
    fetchData() {
      console.log(
        `加载第 ${this.currentPage} 页，每页 ${this.pageSize} 条数据`
      );
    },
  },
};
</script>

<style scoped lang="scss">
.ai-reply-container {
  height: 100%;
  padding: 24px;

  .ai-reply-card {
    display: flex;
    flex-direction: column;
    height: 100%;
    box-sizing: border-box;

    .ai-reply-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .header-title {
        display: flex;

        .section-label {
          font-size: 0.125rem;
          font-weight: 700;
          color: #454545;
          margin-right: 10px;
        }

        .preview-toggle-btn {
          background: #0d4c80;
          font-size: 0.0972rem;
          font-weight: 600;
          color: #f5f2ea;
          padding: 0.0278rem 0.0833rem;
          border-radius: 4px;
        }
      }

      .header-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .feedback-icon {
          margin-left: 8px;
        }
      }
    }

    .form-fields-container {
      margin-top: 24px;
      height: calc(100% - 120px);

      .form-group {
        margin-bottom: 16px;

        .form-label {
          font-weight: 600;
          font-size: 0.0694rem;
          color: #454545;
          display: block;
          margin-bottom: 4px;
        }

        .form-control-wrapper {
          display: flex;
          align-items: center;
        }

        .form-textarea,
        .form-input {
          width: 100%;
          padding: 8px;
          border: 1px solid #ddd;
          border-radius: 10px;
        }

        .form-textarea {
          width: 100%;
          padding: 8px;
          border: 1px solid #ddd;
          border-radius: 10px;
          resize: none;

          &.title-textarea {
            min-height: 30px;
            max-height: 60px;
            &::-webkit-scrollbar {
              display: none;
            }
            scrollbar-width: none; /* Firefox */
          }

          &.start-textarea {
            min-height: 100px;
            max-height: 200px;
          }

          &.main-textarea {
            min-height: 200px;
            max-height: 300px;
          }

          &.ending-textarea {
            min-height: 30px;
            max-height: 60px;
            &::-webkit-scrollbar {
              display: none;
            }
            scrollbar-width: none; /* Firefox */
          }
        }

        .compact-pagination {
          display: flex;
          justify-content: flex-end;
          margin-top: 4px;

          margin-left: 5px;

          .pagination-icon {
            font-size: 0.0833rem;
            color: #6a6969;
            cursor: pointer;
            transition: color 0.2s;

            &:active {
              color: #000;
              transform: scale(0.9);
            }

            &:hover {
              color: #000;
            }
          }

          .pagination-info.compact {
            font-size: 0.0694rem;
            color: #6a6969;
            padding: 2px 4px;
            font-weight: 600;
            border-radius: 4px;
          }
        }
      }
    }

    .action-bar {
      display: flex;
      align-items: end;
      justify-content: space-between;
      margin-top: 16px;
      box-sizing: border-box;
      padding: 8px 0;

      .language-selection {
        padding: 6px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
      }

      .action-buttons {
        display: flex;
        align-items: center;

        .action-btn {
          padding: 0.0278rem 0.0833rem;
          border: none;
          border-radius: 4px;
          cursor: pointer;

          &.edit-btn {
            background-color: #0d4c80;
            margin-right: 12px;
            font-size: 0.0972rem;
            font-weight: 600;
            color: #f5f2ea;
          }

          &.send-btn {
            background-color: #0d4c80;
            font-size: 0.0972rem;
            font-weight: 600;
            color: #f5f2ea;
          }
        }
      }
    }
  }
}
</style>
    